﻿using System;
using System.Drawing;

namespace com.uplus.common
{
    /// <summary>
    /// 提供数据转换服务
    /// @赵晨亮, 2009-07-09
    /// </summary>
    public class Converter
    {
        public static T To<T>(object obj, T defaultValue)
        {
            try
            {
                object re = Convert.ChangeType(obj, typeof(T));
                return (T)re;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static Rectangle ToRectangle(string rect)
        {
            Rectangle r = new Rectangle();
            string[] ts = rect.Split(',');
            if (ts.Length >= 4)
            {
                r.X = To<int>(ts[0], 0);
                r.Y = To<int>(ts[1], 0);
                r.Width = To<int>(ts[2], 0);
                r.Height = To<int>(ts[3], 0);
            }
            return r;
        }

        public static Size ToSize(string size)
        {
            Size s = new Size();
            string[] ts = size.Split(',');
            if (ts.Length >= 2)
            {
                s.Width = To<int>(ts[0], 0);
                s.Height = To<int>(ts[1], 0);
            }
            return s;
        }

        #region TimeSpan转换成时间
        /// <summary>
        /// 根据TimeSpan字符串，获取DateTime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);

            return dateTimeStart.Add(toNow);
        }
        #endregion

        #region 时间戳Timestamp转换成日期  
        public static DateTime GetTime(long TimeStamp, bool AccurateToMilliseconds = false)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            if (AccurateToMilliseconds)
            {
                return startTime.AddTicks(TimeStamp * 10000);
            }
            else
            {
                return startTime.AddTicks(TimeStamp * 10000000);
            }
        }
        #endregion

        // <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>long</returns>
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;  //除10000调整为13位  
            return t;
        }
    }
}
